# 练习1：统计各字符出现的次数 并 找出出现次数最多的几个字符

# step1:
chars = ['a', 'c', 'a', 'b', 'c', 'a', 'b', 'z', 'y', 'k', 'v', 'v', 'k', 'a', 'b', 'b']
# 1
di = {}
for ch in chars:
    if ch in di.keys():
        di[ch] += 1
    else:
        di[ch] = 1
print(di)
# 2
di2 = {}
for ch in chars:
    if ch not in di2:
        di2[ch] = chars.count(ch)
print(di2)

# step 2
vs = di.values()
print(vs)
MaxCount = max(vs)  # 使用内置函数max找到最大值
print(MaxCount)
for k, v in di.items():
    if v == MaxCount:
        print(k)

# 练习2：将姓名年龄存入list，如果姓名已存在，则提示
person = [{'name': 'admin', 'age': 999}]
# 方法一、C的习惯
while True:
    name = input('enter your name: ')
    if name == 'admin':
        break
    i = 0
    while i < len(person):
        if name == person[i]['name']:
            print('姓名已存在')
            break
        i += 1
        if i == len(person):
            age = int(input('enter your age: '))
            p = [{'name': name, 'age': age}]
            person += p
            break
print(person)

# 方法二：python习惯
while True:
    name = input('enter your name: ')
    if name == 'admin':
        break
    for individual in person:
        if individual['name'] == name:
            print('姓名已存在')
            break
    else:
        age = int(input('enter your age: '))
        p = [{'name': name, 'age': age}]
        person += p
print(person)

# 练习3：dict的key和value互换
di = {'name': 'lzy', 'age': 23}
# {'name': 'lzy', 'age': 23}==>{'lzy': 'name', 23: 'age'}
# 方法1. 使用中介dict
temp_di = {}
for k in di:
    value, key = k, di[k]
    temp_di[key] = value
di.clear()
di = temp_di
print(di)
# 方法2. 使用推导式
di = {v: k for k, v in di.items()}
print(di)
